package com.ruoyi.web.web.controller.admin;

import com.ruoyi.accountant.domain.User;
import com.ruoyi.accountant.service.UserService;
import com.ruoyi.web.web.dto.MessageDto;
import com.ruoyi.web.web.form.UserListForm;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Controller("adminUserController")
@RequestMapping("/admin/user")
public class UserController {
    @Autowired
    private UserService userService;

    /****
     * 显示用户列表
     * @param userListForm
     * @return
     */
    @PostMapping("/list")
    @ResponseBody
    public List<User> list(@RequestBody UserListForm userListForm) {
        PageHelper.startPage(userListForm.getOffset(), userListForm.getLimit());
        List<User> users = userService.findAllBy(userListForm);
        PageInfo<User> allBy=new PageInfo<>(users);
        return allBy.getList();
    }


    /***
     * 添加用户
     * @param user
     * @return
     */
    @PostMapping("/add")
    public String add(User user) {
        userService.save(user);
        return "pages/admin/user";
    }

    /***
     * 修改用户信息
     * @param user
     * @return
     */
    @PostMapping("/modify")
    public String modify(User user) {
        User u = userService.findByUid(user.getUid());

        u.setModifytime(new Timestamp(System.currentTimeMillis()));
        u.setUpass(user.getUpass());
        u.setRoleName(user.getRoleName());
        u.setUname(user.getUname());

        userService.update(u);

        return "pages/admin/user";
    }

    /***
     * 创建和修改接口调用key
     * @param uid
     */
    @PostMapping("/createapi")
    @ResponseBody
    public MessageDto createapi(long uid) {
        User byUid = userService.findByUid(uid);
        if(byUid != null) {
            byUid.setApiKey(UUID.randomUUID().toString().replace("-",""));
            userService.update(byUid);
        }
        return MessageDto.ok();
    }

    @PostMapping("/delete")
    @ResponseBody
    public MessageDto delete(String uids) {
        if(!StringUtils.isEmpty(uids)) {
            String[] split = uids.split(",");
            List<Long> values = new ArrayList<>();
            for (String s : split) {
                values.add(Long.parseLong(s));
            }
            userService.deleteAll(values);
        }
        return MessageDto.ok();
    }
}
